/*
 * @Date: 2023-07-10 15:38:38
 * @LastEditors: bb_c_e_f 18434367522@163.com
 * @LastEditTime: 2023-12-14 16:47:31
 * @FilePath: \part-cloud-app\src\api\request.ts
 */
import HttpRequest from 'luch-request'
import type { HttpError, HttpRequestConfig, HttpResponse, HttpTask } from 'luch-request'
import { useAppStore } from '@/stores/app-store'
import { baseUrl } from '@/config/index'

export const BASE_URL = baseUrl

const PoorCode200 = (CODE: number) => CODE === 200 || 500
const requestInstence = new HttpRequest({
  baseURL: BASE_URL,
  timeout: 10 * 1000,
  header: {
    'Content-Type': 'application/json;charset=utf-8',
  },
})

requestInstence.interceptors.request.use(
  (config: HttpRequestConfig) => {
    const appStore = useAppStore()
    const {
      custom: { notLoading },
    } = config as HttpRequestConfig & { custom: Api.Config }
    // 默认需要Loading。。。
    notLoading || uni.showLoading({ title: '加载中...', mask: true })
    config.header = { ...config.header, Authorization: `${appStore.state.token}` }
    return config
  },
  (error: HttpRequestConfig<HttpTask> | HttpError) => Promise.reject(error),
)

requestInstence.interceptors.response.use(
  (response: HttpResponse) => {
    const appStore = useAppStore()
    uni.hideLoading()
    const { data } = response
    if (data.code === 500)
      uni.showToast({ title: data.msg || '请联系后台管理员', icon: 'none', duration: 2500 })

    if (data.code === 401) {
      appStore.clearToken()
      appStore.login().then(async () => {
        // uni.showToast({ title: '请重试', icon: 'none', duration:1500 })
      })
    }
    return PoorCode200(data.code) && data
  },
  (error: HttpError) => {
    uni.hideLoading()
    uni.showToast({ title: '网络君出小差了...', icon: 'none' })
    return Promise.reject(error)
  },
)

export default requestInstence
